<template>
  <div class="editor-container">
    <el-form 
      ref="formRef"
      :model="formData" 
      :rules="formRules"
      label-width="100px"
      class="editor-form"
    >
      <!-- 共用字段 -->
      <el-form-item label="物品名称" prop="itemName" required>
        <el-input v-model="formData.itemName" placeholder="请输入物品名称" />
      </el-form-item>

      <el-form-item label="物品类别" prop="itemCategory">
        <el-select 
          v-model="formData.itemCategory" 
          placeholder="请选择类别"
          style="width: 100%"
        >
          <el-option label="电子产品" value="电子产品" />
          <el-option label="证件" value="证件" />
          <el-option label="书籍" value="书籍" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>

      <!-- 修改地点字段 -->
      <el-form-item 
        :label="isLostType ? '丢失地点' : '捡拾地点'" 
        prop="location"
        required
      >
        <el-input 
          v-model="formData.location" 
          :placeholder="`请输入${isLostType ? '丢失' : '捡拾'}地点`" 
        />
      </el-form-item>

      <el-form-item 
        :label="isLostType ? '送达地点' : '领取地点'"
        prop="locate"
        required
      >
        <el-input 
          v-model="formData.locate" 
          :placeholder="`请输入${isLostType ? '送达' : '领取'}地点详细位置`" 
        />
      </el-form-item>

      <!-- 修改时间字段 -->
      <el-form-item 
        :label="isLostType ? '丢失时间' : '捡拾时间'" 
        prop="time"
        required
      >
        <el-date-picker
          v-model="formData.time"
          type="datetime"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
          :placeholder="`选择${isLostType ? '丢失' : '捡拾'}时间`"
        />
      </el-form-item>

      <el-form-item label="详细描述" prop="detailedDescription">
        <el-input
          v-model="formData.detailedDescription"
          type="textarea"
          :rows="4"
          placeholder="请输入详细描述"
        />
      </el-form-item>

      <el-form-item label="物品图片" prop="image">
        <el-upload
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleImageChange"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">支持 JPG/PNG 格式，大小不超过 2MB</div>
          </template>
        </el-upload>
        <img 
          v-if="formData.imagePreview" 
          :src="formData.imagePreview" 
          class="image-preview"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { UploadFile } from 'element-plus'
import axios from 'axios'

interface ItemData {
  id?: number
  itemName: string
  itemCategory: string
  detailedDescription: string
  location: string  // 统一地点字段
  time: string      // 统一时间字段
  locate: string    // 定位字段
  image: string
  imagePreview?: string
  imageFile?: File
}

const route = useRoute()
const router = useRouter()
const formRef = ref()
const token = localStorage.getItem('token');
// 表单数据
const formData = ref<ItemData>({
  itemName: '',
  itemCategory: '',
  detailedDescription: '',
  location: '',
  time: '',
  locate: '',
  image: ''
})

// 类型判断
const isLostType = computed(() => route.query.type === 'lost')

// 使用计算属性生成验证规则
const formRules = computed(() => {
  return {
    itemName: [{ required: true, message: '物品名称不能为空', trigger: 'blur' }],
    
    // 统一使用 location 字段
    location: [{ 
      required: true, 
      message: isLostType.value ? '丢失地点不能为空' : '捡拾地点不能为空', 
      trigger: 'blur' 
    }],
    
    // 统一使用 time 字段
    time: [{ 
      required: true, 
      message: isLostType.value ? '请选择丢失时间' : '请选择捡拾时间', 
      trigger: 'change' 
    }],
    
    // 定位字段验证
    locate: [{ 
      required: true, 
      message: isLostType.value ? '送达地点不能为空' : '领取地点不能为空', 
      trigger: 'blur' 
    }]
  }
})

// 监听类型变化并重置验证
watch(() => route.query.type, () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
})

// 初始化加载
onMounted(async () => {
  const id = route.params.id || route.query.id
  if (id) {
    try {
      const apiPath = isLostType.value ? 'lost' : 'find'
      const { data } = await axios.get(`/${apiPath}/ById/${id}`,{
        headers: {
        Authorization: `Bearer ${token}`  // 在请求头中添加 Token
      }
      })
      
      formData.value = {
        ...data,
        location: isLostType.value ? data.lostLocation : data.foundLocation,
        time: isLostType.value ? data.lostTime : data.foundTime,
        locate: data.locate || '',
        imagePreview: data.image ? `http://localhost:8080/${data.image}` : ''
      }
    } catch (error) {
      ElMessage.error('数据加载失败')
    }
  }
})

// 图片处理
const handleImageChange = (file: UploadFile) => {
  if (file.raw) {
    const reader = new FileReader()
    reader.onload = () => {
      formData.value.imagePreview = reader.result as string
      formData.value.imageFile = file.raw
    }
    reader.readAsDataURL(file.raw)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();

    // 构建 FormData
    const formPayload = new FormData();

    formPayload.append("itemName", formData.value.itemName);
    formPayload.append("itemCategory", formData.value.itemCategory);
    formPayload.append(
      isLostType.value ? "lostLocation" : "foundLocation",
      formData.value.location
    );
    
    // 添加定位字段
    formPayload.append("locate", formData.value.locate || '');
    
    formPayload.append(
      isLostType.value ? "lostTime" : "foundTime",
      formData.value.time
    );
    formPayload.append("detailedDescription", formData.value.detailedDescription);

    // 添加图片文件（如果有）
    if (formData.value.imageFile) {
      formPayload.append("image", formData.value.imageFile);
    }

    // 显式使用 POST 方法
    const apiPath = isLostType.value ? "lost" : "find";
    const isEdit = !!formData.value.id;
    if (!route.query.type) {
      ElMessage.error('操作类型无效');
      router.push('/home');
    }
    if (isEdit) {
      await axios.put(`/${apiPath}/update/${formData.value.id}`, formPayload, {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
    } else {
      await axios.post(`/${apiPath}/add`, formPayload, {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
    }

    ElMessage.success(isEdit ? "修改成功" : "新增成功");
    router.back();
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请检查表单");
  }
};

// 取消操作
const handleCancel = () => {
  router.back()
}
</script>



<style scoped>
.editor-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  max-width: 800px;
  margin: 20px auto;
}

.editor-form {
  padding: 20px;
}

.image-preview {
  margin-top: 10px;
  max-width: 200px;
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.el-upload__tip {
  color: #666;
  font-size: 12px;
  margin-top: 5px;
}

/* 必填星号样式 */
:deep(.el-form-item.is-required .el-form-item__label:before) {
  content: "*";
  color: #F56C6C;
  margin-right: 4px;
}
</style>